package cn.wondertek.auth.controller;

import cn.wondertek.common.core.domain.R;
import cn.wondertek.common.redis.util.RedisUtils;
import cn.wondertek.common.utils.PatternUtil;
import cn.wondertek.common.utils.http.HttpUtils;
import cn.wondertek.common.utils.sms.VerifyCodeUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

/**
 * @author chengtao
 */
@RestController
@RequestMapping("sms")
public class SmsCodeController {
    @Autowired
    private RedisUtils redis;

    @PostMapping("/smsCode")
    public R login(@RequestBody String mobile) {
        //生成短信码
        if (StringUtils.isNotBlank(mobile)) {
            try {
                String verifyCode = VerifyCodeUtil.generateTextCode(VerifyCodeUtil.TYPE_NUM_ONLY, 6, null);
                if(!PatternUtil.isMobile(mobile)){
                    return R.error("手机号码不合法");
                }

                /*String count = redis.set("auth::mobile::code::map",mobile);
                if(count == null){
                    redisServiceCode.mapPut(RedisDao.MAP_MOBILE_CODE,mobile,"1");
                }else if (Integer.valueOf(count)>=6){
                }else {
                    redisServiceCode.mapPut(RedisDao.MAP_MOBILE_CODE,mobile,""+(Integer.valueOf(count)+1));
                }*/
                redis.set("auth::mobile::code::map::" + mobile, verifyCode, 5 * 60);

                //发送短信
                HashMap<String,Object> result = sendSms(mobile,verifyCode);
                if ("160040".equals(result.get("statusCode"))) { //发送失败
                    //session.removeAttribute(Const.SESSION_SECURITY_CODE);//移除SESSION的验证
                    redis.delete("auth::mobile::code::map::" + mobile);
                    return R.error("超出同号码每天发送上限");
                }else if ("160038".equals(result.get("statusCode"))){
                    //session.removeAttribute(Const.SESSION_SECURITY_CODE);//移除SESSION的验证
                    redis.delete("auth::mobile::code::map::" + mobile);
                    return R.error("验证码发送频繁");
                }

                return R.data(verifyCode);

            } catch (Exception e) {
                e.printStackTrace();
                return R.error("错误发送验证码");
            }

        } else {
            return R.error("手机号码为空！");
        }

    }

    /**
     * 发送短信验证码
     * 调用阿里云短信服务
     *
     * @param mobileNo
     * @param code
     * @return
     */
    private HashMap<String,Object> sendSms(String mobileNo,String code) {
        boolean flag = false;
        HashMap<String, Object> result = new HashMap<>();
	/*	CCPRestSDK restAPI = CCPRestSDK.getInstance();
		restAPI.init("app.cloopen.com", "8883");// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
		restAPI.setAccount("8aaf070863f8fb0401641accf2d21625", "081c6ef3bdd440ec968a3894ec3de9c4");// 初始化主帐号和主帐号TOKEN
		restAPI.setAppId("8aaf070863f8fb0401641accf333162c");// 初始化应用ID
		result = restAPI.sendTemplateSMS(mobileNo,"355196" ,new String[]{code,"5"});
		logger.debug("SDKTestSendTemplateSMS result=" + result);



*/

        String accessKeyId = "LTAI4G9VqRbSkugGNyKXC3Gm";//移动传播平台
//		String accessKeyId = "LTAI4G7UZJyHhESptLXc2zTC";//安徽卫视
        String accessSecret = "6DSVX7zfBR8xc637BjkAOK53VK2xcE";
        //String accessSecret = "1Gq3VyZagk99ZLLoxzjUyS8GQQzydo";//安徽卫视
        java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));// 这里一定要设置GMT时区
        java.util.Map<String, String> paras = new java.util.HashMap<String, String>();
        // 1. 系统参数
        paras.put("SignatureMethod", "HMAC-SHA1");
        paras.put("SignatureNonce", java.util.UUID.randomUUID().toString());
        paras.put("AccessKeyId", accessKeyId);
        paras.put("SignatureVersion", "1.0");
        paras.put("Timestamp", df.format(new java.util.Date()));
        paras.put("Format", "JSON");
        // 2. 业务API参数
        paras.put("Action", "SendSms");
        paras.put("Version", "2017-05-25");
        paras.put("RegionId", "cn-hangzhou");
        paras.put("PhoneNumbers", mobileNo);
//		paras.put("SignName", "安徽卫视");
        paras.put("SignName", "网达移动传播平台");
        paras.put("TemplateParam", "{\"code\":\""+code+"\"}");



//		paras.put("TemplateCode", "SMS_189615478");//安徽卫视
        paras.put("TemplateCode", "SMS_189026803");//移动传播平台
        // 3. 去除签名关键字Key
        if (paras.containsKey("Signature"))
            paras.remove("Signature");
        // 4. 参数KEY排序
        java.util.TreeMap<String, String> sortParas = new java.util.TreeMap<String, String>();
        sortParas.putAll(paras);
        // 5. 构造待签名的字符串
        java.util.Iterator<String> it = sortParas.keySet().iterator();
        StringBuilder sortQueryStringTmp = new StringBuilder();
        while (it.hasNext()) {
            String key = it.next();
            try {
                sortQueryStringTmp.append("&").append(specialUrlEncode(key)).append("=").append(specialUrlEncode(paras.get(key)));
                String sortedQueryString = sortQueryStringTmp.substring(1);// 去除第一个多余的&符号
                StringBuilder stringToSign = new StringBuilder();
                stringToSign.append("GET").append("&");
                stringToSign.append(specialUrlEncode("/")).append("&");
                stringToSign.append(specialUrlEncode(sortedQueryString));
                String sign = sign(accessSecret + "&", stringToSign.toString());
                // 6. 签名最后也要做特殊URL编码
                String signature = specialUrlEncode(sign);
                String s = HttpUtils.sendGet("http://dysmsapi.aliyuncs.com", "Signature=" + signature + sortQueryStringTmp);
                System.out.println("-----------------------------------------" + s);
                if (s.contains("OK")){
                    result.put("statusCode","000000");
                }else {
                    result.put("statusCode", "160040");
                }
            } catch (Exception e) {
                result.put("statusCode", "160040");
                e.printStackTrace();
            }
        }
        return result;
    }


    public static String specialUrlEncode(String value) throws Exception {
        return java.net.URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
    }
    public static String sign(String accessSecret, String stringToSign) throws Exception {
        javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
        mac.init(new javax.crypto.spec.SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        return new sun.misc.BASE64Encoder().encode(signData);
    }
}
